const { app, BrowserWindow, Tray, Menu, shell } = require('electron');
const path = require('path');
const { spawn } = require('child_process');
const express = require('express');
const mysql = require('mysql2');
const cors = require('cors');

let mainWindow;
let tray;
let serverProcess;

// 启动后端服务
function startServer() {
  const server = express();
  const port = 3000;

  // 中间件
  server.use(cors());
  server.use(express.json());

  // MySQL 连接配置
  const connection = mysql.createConnection({
    host: '127.0.0.1',
    user: 'root',
    password: '88888888',
    database: 'chromenodebook',
    charset: 'utf8mb4'
  });

  // 连接数据库
  connection.connect((err) => {
    if (err) {
      console.error('数据库连接失败:', err);
      return;
    }
    console.log('成功连接到 MySQL 数据库');
  });

  // API 路由：保存笔记
  server.post('/api/notes', (req, res) => {
    const { title, type, keywords, content, thoughts } = req.body;
    
    const query = `
      INSERT INTO node_book (title, type, key_list, content, think) 
      VALUES (?, ?, ?, ?, ?)
    `;
    
    connection.query(query, [title, type, keywords, content, thoughts], (err, results) => {
      if (err) {
        console.error('保存笔记失败:', err);
        res.status(500).json({ 
          success: false, 
          message: '保存失败: ' + err.message 
        });
        return;
      }
      
      console.log('笔记保存成功，ID:', results.insertId);
      res.json({ 
        success: true, 
        message: '笔记保存成功',
        id: results.insertId 
      });
    });
  });

  // API 路由：获取所有笔记
  server.get('/api/notes', (req, res) => {
    const query = 'SELECT * FROM node_book ORDER BY id DESC';
    
    connection.query(query, (err, results) => {
      if (err) {
        console.error('获取笔记失败:', err);
        res.status(500).json({ 
          success: false, 
          message: '获取失败: ' + err.message 
        });
        return;
      }
      
      res.json({ 
        success: true, 
        data: results 
      });
    });
  });

  // 启动服务器
  server.listen(port, () => {
    console.log(`服务器运行在 http://127.0.0.1:${port}`);
  });

  // 优雅关闭
  process.on('SIGINT', () => {
    connection.end();
    process.exit();
  });
}

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    },
    icon: path.join(__dirname, 'icon128.png')
  });

  // 启动后端服务
  startServer();

  // 加载插件页面
  mainWindow.loadFile('popup.html');

  // 创建系统托盘
  createTray();

  mainWindow.on('closed', () => {
    mainWindow = null;
  });
}

function createTray() {
  tray = new Tray(path.join(__dirname, 'icon16.png'));
  const contextMenu = Menu.buildFromTemplate([
    {
      label: '打开插件',
      click: () => {
        if (mainWindow) {
          mainWindow.show();
        } else {
          createWindow();
        }
      }
    },
    {
      label: '打开浏览器插件管理',
      click: () => {
        shell.openExternal('chrome://extensions/');
      }
    },
    { type: 'separator' },
    {
      label: '退出',
      click: () => {
        app.quit();
      }
    }
  ]);
  tray.setToolTip('Chrome 笔记插件');
  tray.setContextMenu(contextMenu);
}

app.whenReady().then(createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

app.on('before-quit', () => {
  if (serverProcess) {
    serverProcess.kill();
  }
}); 